package net.zigin.nhi.waste.view.rfid;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gyf.immersionbar.ImmersionBar;
import com.rfid.trans2000.ReadTag;
import com.rfid.trans2000.TagCallback;
import com.rfid.trans2000.UHFLib;

import net.zigin.nhi.waste.R;
import net.zigin.nhi.waste.constants.Constants;
import net.zigin.nhi.waste.utils.Reader;

import java.util.HashSet;
import java.util.Set;

import io.paperdb.Paper;

public class ScanRfidActivity extends AppCompatActivity {

    private LinearLayout mScan;
    private LinearLayout mResultLayout;
    private TextView mCount;
    private Button mStop;
    private LinearLayout mScanLayout;
    private TextView mConnecting;

    private int maxAntennaNum = 4;
    private Set<String> epcSet = new HashSet<>();
    private Handler mHandler = new MyHandler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_rfid);
        initView();
        initData();
    }

    private void initView() {
        ImmersionBar.with(this).init();
        mScan = findViewById(R.id.scan);
        mResultLayout = findViewById(R.id.result_layout);
        mCount = findViewById(R.id.count);
        mStop = findViewById(R.id.stop);
        mScanLayout = findViewById(R.id.scan_layout);
        mConnecting = findViewById(R.id.connecting);
        mScan.setEnabled(false);
    }

    private void initData() {
        connect();
        epcSet.clear();
        mScan.setOnClickListener(v -> {
            if (mScanLayout.getVisibility() == View.VISIBLE) {
                mScan.setEnabled(false);
                MsgCallback callback = new MsgCallback();
                Reader.rrlib.SetCallBack(callback);
                if (Reader.rrlib.StartRead() == 0) {
                    maxAntennaNum = Reader.rrlib.GetInventoryPatameter().MaxAntennaNum;
                }
            } else {
                mConnecting.setText("连接中...");
                mScan.setEnabled(false);
                connect();
            }
        });

        mStop.setOnClickListener(v -> {
            mScan.setEnabled(true);
            Reader.rrlib.StopRead();
            for (String s : epcSet) {
                Log.i("epc扫描结果", s);
            }
            Paper.book().write(Constants.EPCS, epcSet);
            Intent intent = new Intent(ScanRfidActivity.this, RfidBatchActivity.class);
            startActivity(intent);
            finish();
        });
    }

    private void connect() {
        new Thread(() -> {
            byte[] data = new byte[1];
            Reader.rrlib = new UHFLib(1, "");
            int result = Reader.rrlib.Connect("192.168.0.250", 27011);
            data[0] = (byte) (result);
            mHandler.obtainMessage(0, 1, -1, data).sendToTarget();
        }).start();
    }

    @SuppressLint("HandlerLeak, SetTextI18n")
    private class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                byte[] buffer = (byte[]) msg.obj;
                if (buffer[0] == 0) {
                    mScan.setEnabled(true);
                    mScanLayout.setVisibility(View.VISIBLE);
                    mConnecting.setVisibility(View.GONE);
                } else {
                    mScan.setEnabled(true);
                    mScanLayout.setVisibility(View.GONE);
                    mConnecting.setVisibility(View.VISIBLE);
                    mConnecting.setText("重连");
                    Toast.makeText(getApplication(), "连接失败！", Toast.LENGTH_SHORT).show();
                }
            } else if (msg.what == 1) {
                mScan.setVisibility(View.GONE);
                mResultLayout.setVisibility(View.VISIBLE);
                mCount.setText(epcSet.size() + "");
            }
        }
    }

    public class MsgCallback implements TagCallback {
        @Override
        public void tagCallback(ReadTag arg0) {
            String epc = arg0.epcId.toUpperCase();
            String DevName = arg0.DevName;
            epcSet.add(epc);
            Message msg = new Message();
            msg.what = 1;
            msg.obj = epcSet;
            mHandler.sendMessage(msg);
        }

        @Override
        public int tagCallbackFailed(int reason) {
            return 0;
        }

        @Override
        public void ReadOver() {
            mScan.setEnabled(true);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Reader.rrlib.StopRead();
        Reader.rrlib.DisConnect();
    }
}